package br.com.gbvbahia.mybooks.adapters;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.gbvbahia.mybooks.R;
import br.com.gbvbahia.mybooks.dao.EditoraDAO;
import br.com.gbvbahia.mybooks.modelos.EditoraVO;
import br.com.gbvbahia.mybooks.modelos.LivroVO;

public class LivroAdapter extends BaseAdapter {

	private List<LivroVO> list;
	private LayoutInflater inflater;
	private EditoraDAO editoraDAO;

	public LivroAdapter(Activity context, List<LivroVO> list) {
		super();
		this.list = list;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		editoraDAO = new EditoraDAO(context);
	}

	public LivroAdapter(Fragment fragment, List<LivroVO> list) {
		this(fragment.getActivity(), list);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		ViewHolder holder = null;
		if (view == null) {
			holder = new ViewHolder();
			int layoutLinha = R.layout.livro_item;
			view = inflater.inflate(layoutLinha, null);
			view.setTag(holder);
			holder.tNome = (TextView) view.findViewById(R.id.tNome);
			holder.tAutor = (TextView) view.findViewById(R.id.tAutor);
			holder.tEditora = (TextView) view.findViewById(R.id.tEditora);
			holder.avlimg = (ImageView) view.findViewById(R.id.avlimg);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		LivroVO vo = list.get(position);
		holder.tNome.setText(vo.getNomeLivro());
		holder.tAutor.setText(vo.getAutorLivro());
		if (vo.getCdEditora() != null) {
			EditoraVO editora = editoraDAO.getByID(vo.getCdEditora());
			if (editora != null)
				holder.tEditora.setText(editora.getNome());
			else
				holder.tEditora.setText("");
		} else {
			holder.tEditora.setText("");
		}if(!StringUtils.isBlank(vo.getAvaliacao())
				&& vo.getNota() > -1){
			holder.avlimg.setImageResource(R.drawable.avaliado_high);
		}else if(!StringUtils.isBlank(vo.getAvaliacao())
				|| vo.getNota() > -1){
			holder.avlimg.setImageResource(R.drawable.avaliado_medium);
		}else {
			holder.avlimg.setImageResource(R.drawable.avaliado_low);
		}
		return view;
	}

	// Design Patter "ViewHolder" para Android
	static class ViewHolder {
		TextView tNome;
		TextView tAutor;
		TextView tEditora;
		ImageView avlimg;
	}
}
